var lesson = new Lesson();

function Lesson(lsn) {
  this.data = lsn;
  if (lsn) {
    this.id = lsn["id"];
    this.title = lsn["title"];
    this.items = lsn["items"] ? lsn["items"].map(function(n, i) {
      var item = new Item(n);
      item.index = i;
      return item;
    }) : [];
    this.tests = this.items.filter(function(n, i) {
      return n.type == "test";
    });
    this.items.current = this.items.length > 0 ? this.items[0] : null;
  }
  this.slides = $("#lesson .slide");
  this.slides.current = this.slides[0];
  this.score_slide = $("#lesson #score_slide");
  $("#lesson").mousedown({ lesson : this }, function(event) { event.data.lesson.mouseDown(event) });
  $("#lesson").mousemove({ lesson : this }, function(event) { event.data.lesson.mouseMove(event) });
  $("#lesson").mouseup({ lesson : this }, function(event) { event.data.lesson.mouseUp(event) });
  this.score = {};
}

Lesson.prototype = {
  show : function() {
    for (var i = 0; i < this.items.length; i++) {
      switch (this.items[i].type) {
        case "info" :
          this.items[i].graphics.show($(this.slides[i + 1]).find(".graphics"));
          break;
        case "test" :
          this.items[i].task.show($(this.slides[i + 1]).find(".task"));
          break;
        default :
          alert("Unrecognized item type. item = " + JSON.stringify(this.items[i]));
      }
    }
    var hash = window.location.hash;
    if (hash == "#score") {
      this.showScore();
      return;
    }
    if (hash.length > 1 && hash != "#index") {
      var item = this.getItem(hash.substring(1));
      if (item) {
        lesson.items.current = item;
        this.showSlide($.inArray(item, lesson.items) + 1);
      }
    }
  },

  edit : function() {
    var hash = window.location.hash;
    if (hash.length > 1 && hash != "#index") {
      var item = this.getItem(hash.substring(1));
      if (item) {
        lesson.items.current = item;
        $("#index, #create_item").hide();
        item.edit();
        $("#item").show();
      } else {
        alert("Item not found.");
      }
    } else {
      $("#index, #create_item").show();
      $("#item").hide();
    }
  },

  editTitle : function() {
    var val = prompt("Enter a new name for this lesson", this.title);
    if (val) {
      this.title = val;
      $.ajax({
        url : "/admin/edit_object?kind=lesson&id=" + lesson.id +
              "&property_name=title&property_value=" + val,
        type : "post",
        success : function(val) {
          lesson.updateTitle();
        }
      });
    }
  },

  updateTitle : function() {
    var span = $('.lesson-title span');
    var full_title = span.html().trim();
    var ix = full_title.indexOf(":");
    if (ix > 0) {
      span.html(full_title.substring(0, ix + 1) + " " + this.title);
    } else {
      window.location.reload = true;
    }
  },

  showSlide : function(ix) {
    if (0 <= ix && ix < this.slides.length) {
      this.slides.current = this.slides[ix];
    }
    if (0 <= ix - 1 && ix - 1 < this.items.length) {
      this.items.current = this.items[ix - 1];
      window.location.hash = this.items.current.id;
    } else {
      window.location.hash = "index";
    }
    for (var i = 0; i < this.slides.length; i++) {
      var cn = "";
      switch(i - ix) {
        case -2 : cn = "slide far-past"; break;
        case -1 : cn = "slide past"; break;
        case  0 : cn = "slide current"; break;
        case  1 : cn = "slide future"; break;
        case  2 : cn = "slide far-future"; break;
        default : cn = "slide hidden"; break;
      }
      this.slides[i].className = cn;
    }
    this.showNavigation();
  },

  showNavigation : function() {
    var score_screen = window.location.hash == "#score";
    var ix = $.inArray(this.slides.current, this.slides);
    var back = $("#lesson #lesson_navigation").find(".back");
    back.attr("enabled", ix > 0 ? "true" : "false");
    back.find("img")[0].src = (ix > 0 && !score_screen) ? "/images/back.png" : "/images/back_gray.png";

    var next = $("#lesson #lesson_navigation").find(".next");
    var item = this.items.current;
    if (!score_screen && (item.type != "test" || item.task.complete)) {
      next.attr("enabled", "true");
      next.find("img")[0].src = "/images/forward.png";
    } else {
      next.attr("enabled", "false");
      next.find("img")[0].src = "/images/forward_gray.png";
    }
  },

  showNextSlide : function(override) {
    var ix = $.inArray(this.slides.current, this.slides);
    if (-1 < ix && ix + 1 < lesson.slides.length) {
      if (override || $("#lesson_navigation").find(".next").attr("enabled") == "true") {
        this.showSlide(ix + 1);
      }
    } else {
      var item = lesson.items[ix - 1];
      if (item && (item.type == "info" || (item.type == "test" && item.task.complete))) {
        this.showScore();
      }
    }
  },

  showPreviousSlide : function() {
    var ix = $.inArray(lesson.slides.current, lesson.slides);
    if (ix > 0) {
      this.showSlide(ix - 1);
    }
  },

  showScore : function() {
    window.location.hash = "score";
    this.score_slide.html("<p class='xxlarge'>Score</p>" +
      "<table style='width:100%'><tr><td>Test name</td>" +
      "<td class='a-center'># of attempts</td><td class='a-center'>Score</td></tr></table>");
    var table = this.score_slide.find("table");
    var item_max_score = 3;
    var total_score = 0;
    for (var i = 0; i < this.tests.length; i++) {
      var task = this.tests[i].task;
      var score = 0;
      if (task.complete) {
        score =  Math.max(4 - task.attempts, 1);
        total_score += score;
      }
      this.score[this.tests[i].id] = score;
      table.append("<tr><td>" + this.tests[i].title + "</td>" +
        "<td class='a-center'>" + task.attempts + "</td>" +
        "<td class='a-center'>" + score + " / " + item_max_score + "</td></tr>");
    }
    this.score.total = total_score;
    this.score.max = this.tests.length * item_max_score;
    var percent_correct = parseInt(100 * total_score / (this.tests.length * item_max_score));
    table.append("<tr><td></td><td colspan='2' class='a-right'>Total : " + total_score + " / " +
      (this.tests.length * item_max_score) + " (" + percent_correct + "%)</td></tr>");
    this.score_slide.append("<div><a onclick='lesson.restart();'>" +
      "<img src='/images/restart.png' style='vertical-align:middle;'></a>" +
      " Restart this lesson</div>");
    this.slides.animate({ opacity : 0 }, 400, function() {
      var score = $("#lesson #score_slide").css({opacity : 0}).show();
      score.animate({ opacity : 1 }, 400);
    });
    this.showNavigation();
  },
  
  getItem : function(id) {
    var items = this.items.filter( function(item) { return item.id == id; } );
    return items.length > 0 ? items[0] : null;
  },

  removeItem : function(id) {
    var item = this.items.filter(function(item) { return item.id == id; } )[0];
    if (confirm("Are you sure you want to remove this item?")) {
      $.ajax({
        url : "/admin/delete_object?kind=item&id=" + id,
        type : "post",
        success : function() { window.location.reload(true) }
      })
    }
  },

  restart : function() {
    window.location.hash = "";
    window.location.reload(true);
/*, function() {
      $("#lesson #score_slide").hide();
      lesson.slides.css({ opacity : 0 }).show();
      lesson.slides.animate({ opacity : 1}, 400);
    });*/
//    this.show();
  },

  saveProperty : function(property_name, property_value) {
    if (!property_value) {
      property_value = JSON.stringify(this[property_name]);
    }
    $.ajax({
      url : "/admin/edit_object?kind=lesson&id=" + this.id +
        "&property_name=" + property_name + "&property_value=" + property_value,
      type : "post",
      success : function() {
//          alert("success!");
      }
    });
  },

  mouseDown : function(event) {

  },

  mouseMove : function(event) {
    var item = lesson.items.current;
    if (item.type == "test" && item.task.mouseMove) {
      item.task.mouseMove(event);
    }
  },

  mouseUp : function(event) {
    var lesson = event.data.lesson;
    lesson.enableSelection();
    var item = lesson.items.current;
    if (item.type == "test" && item.task.mouseUp) {
      item.task.mouseUp(event);
    }
  },

  enableSelection : function() {
    $("#lesson").css({ "-webkit-user-select" : "inherit", "-khtml-user-select": "inherit",
      "-moz-user-select" : "inherit", "-o-user-select" : "inherit", "user-select" : "inherit" });
  },

  disableSelection : function() {
    $("#lesson").css({ "-webkit-user-select" : "none", "-khtml-user-select": "none",
      "-moz-user-select" : "none", "-o-user-select" : "none", "user-select" : "none" });
  }
};